#!/bin/bash
PROJECT_DIR=$(pwd)
PROJECT_NAME=WebHUD
CURRENT_PROJECT_VERSION=0.2
CONFIGURATION=$1
CONFIGURATION_BUILD_DIR=$PROJECT_DIR/build/$CONFIGURATION
DSTROOT=$CONFIGURATION_BUILD_DIR/${PROJECT_NAME}.dst
INSTALL_PATH="Library/InputManagers/WebHUD"

echo "PROJECT_DIR=$PROJECT_DIR"
echo "PROJECT_NAME=$PROJECT_NAME"
echo "CURRENT_PROJECT_VERSION=$CURRENT_PROJECT_VERSION"
echo "DSTROOT=$DSTROOT"

echo -n "correct? C-C to cancel"
read x

test -z "$CONFIGURATION" && {
    echo "You need to choose a build configuration (Debug, Release)"
    exit 10
}
test -d "$DSTROOT/$INSTALL_PATH" || {
    echo "does'nt exist: $DSTROOT/$INSTALL_PATH";
    exit 11;
}

echo "-------------------------------------------------"
tree $DSTROOT
echo "-------------------------------------------------"
echo -n "OK?"
retd x

# fix perms
chmod 1775 "$DSTROOT/Library"
chown -R root:admin "$DSTROOT/Library"
chmod -R 0755 $DSTROOT/$INSTALL_PATH

# create installer package
PKG="$CONFIGURATION_BUILD_DIR/Install WebHUD.pkg"
echo "Creating installer package ..."
packagemaker \
    --root "$DSTROOT" \
    --id "de.inquant.WebHUD" \
    --version "$CURRENT_PROJECT_VERSION" \
    --target 10.5 \
    --no-recommend \
    --title "WebHUD" \
    --out "$PKG"
echo "Package: `ls -la "$PKG"`"

echo "Creating Disk Image ..."
# clean old package and mount DMG
rm -f "$CONFIGURATION_BUILD_DIR/WebHUD_$CURRENT_PROJECT_VERSION.dmg"
cp "$PROJECT_DIR/Installer/WebHUD.dmg" "$CONFIGURATION_BUILD_DIR/WebHUD.temp.dmg"
hdiutil attach -quiet "$CONFIGURATION_BUILD_DIR/WebHUD.temp.dmg"

# copy installer package
cp "$PKG" "/Volumes/WebHUD/Install WebHUD.pkg"

# copy readme and history file
cp "$PROJECT_DIR/README.rtf" /Volumes/WebHUD
cp "$PROJECT_DIR/HISTORY.txt" /Volumes/WebHUD

# copy examples
cp -R "$PROJECT_DIR/Examples" /Volumes/WebHUD

# recreate DMG
hdiutil detach -quiet "/Volumes/WebHUD"
hdiutil resize -quiet -sectors min "$CONFIGURATION_BUILD_DIR/WebHUD.temp.dmg"
hdiutil convert -quiet "$CONFIGURATION_BUILD_DIR/WebHUD.temp.dmg" -format UDBZ \
         -o "$CONFIGURATION_BUILD_DIR/WebHUD_$CURRENT_PROJECT_VERSION.dmg"

# cleanup
echo "Cleanup ..."
rm -f "$CONFIGURATION_BUILD_DIR/WebHUD.temp.dmg"
rm -f "$CONFIGURATION_BUILD_DIR/Install WebHUD.pkg"

echo "DMG: $CONFIGURATION_BUILD_DIR/WebHUD_$CURRENT_PROJECT_VERSION.dmg"


